package com.horizon.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * @author Administrator
 * @date 2021/9/5
 */
public class JsonUtil {
    // 谷歌的GsonBuilder構造器
    static GsonBuilder gb = new GsonBuilder();
    private static final Gson gson;
    static {
        // 不需要html escape
        gb.disableHtmlEscaping();
        gson = gb.create();
    }

    // Object對象轉換成json字符串后，进一步转换成字节数组
    public static byte[] object2JsonBytes(Object obj) {
        // 把对象转换成json
        String json = pojoToJson(obj);
        try {
            return json.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    // pojo轉換成字符串
    public static String pojoToJson(Object obj) {
        String json = gson.toJson(obj);
        return json;
    }

    // bytes转object
    public static <T> T jsonBytes2Object(byte[] bytes, Class<T> tClass) {
        try {
            String json = new String(bytes, "UTF-8");
            T t = jsonToPojo(json, tClass);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // json转obj
    public static <T> T jsonToPojo(String json, Class<T> tClass) {
        T t = gson.fromJson(json, tClass);
        return t;
    }

    // ali的fastjson
    public static <T> T jsonToPojo(String json, TypeReference<T> type) {
        T t = JSON.parseObject(json, type);
        return t;
    }

    // gson的另外一种转换obj方式
    public static <T> T jsonToPojo(String json, Type type) {
        T t = gson.fromJson(json, type);
        return t;
    }
}
